#include "Socket.hpp"

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        cout << "需要输入ip和端口号,./xx.exe ip port\n";
        exit(0);
    }
    string ip = argv[1];
    uint16_t port = stoi(argv[2]);
    Socket socket;
    socket.CreateSocket();
    bool r = socket.Connect(ip, port);
    if (!r)
    {
        cout << "connect fail!\n";
        return 1;
    }

    srand(time(nullptr) ^ getpid());
    int cnt = 10;
    char opr[] = {'+', '-', '*', '/', '%', '^', '&'};
    int olen = sizeof(opr);
    string in_str;
    while (cnt--)
    {
        std::cout << "第" << cnt << "次测试" << endl;
        sleep(1);
        int x = rand() % 10 + 1, y = rand() % 100 + 5;
        char op = opr[rand() % olen];
        Request q(x, y, op);
        q.CreateTask();
        string out;
        q.Serialize(&out); // 序列化
        out = Encode(out); // 添加报头
        cout << "这是最新的发出去的请求:\n" << out;

        write(socket.GetSocketfd(), out.c_str(), out.size());
       // write(socket.GetSocketfd(), out.c_str(), out.size());
     //   write(socket.GetSocketfd(), out.c_str(), out.size());
       // write(socket.GetSocketfd(), out.c_str(), out.size());

        char buff[128];
        ssize_t n = read(socket.GetSocketfd(), buff, sizeof(buff));
        if (n > 0)
        {
            buff[n] = 0;
            in_str += buff;
            string res;
            bool rr = Decode(in_str, &res);
            if (!rr)  cout << "Decode fail" << in_str << endl;
            assert(rr);

            Response r;
            rr = r.Reserialize(res);
            if (!rr)  cout << "Reserialize fail" << in_str << endl, sleep(100);

            cout << "结果响应完成,result:" << r.res << " code:" << r.code << endl;
        }
    }
    socket.Close();

    return 0;
}